﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using TaoSH.Data;
using System.Text;

namespace TaoSH.AppCode
{

    #region 系统模块
    //用户表
    public class JH_Auth_UserB : BaseEFDao<JH_Auth_User>
    {



        public class UserInfo
        {
            public JH_Auth_User User;
            public string UserRoleCode;

            public UserInfo(string strUserName)
            {
                User = new JH_Auth_UserB().GetEntity(d => d.UserName == strUserName);
                UserRoleCode = new JH_Auth_UserRoleB().GetRoleCodeByUserName(strUserName);
            }

        }
        public string GetUserRealName(string strUserName)
        {
            return strUserName == "" ? "" : new JH_Auth_UserB().GetEntity(d => d.UserName == strUserName).UserRealName;
        }
        public string GetUserRealNames(string[] arrUserName)
        {
            string strReturn = "";
            foreach (var item in arrUserName)
            {
                strReturn = strReturn + GetUserRealName(item) + ",";
            }
            return strReturn.TrimEnd(',');
        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        public string GetAllUser()
        {
            string strUserJson = "";
            DataTable dt = new DataTable();
            strUserJson = new JH_Auth_UserB().GetDTByCommand(" select id, UserName, UserRealName, BranchCode, IsUse, zhiwu,JH_Auth_Branch.DeptName  from JH_Auth_User LEFT JOIN JH_Auth_Branch on JH_Auth_User.BranchCode=JH_Auth_Branch.DeptCode ").ToJson();
            return strUserJson;
        }

        /// <summary>
        /// 获取前端需要的人员选择列表
        /// </summary>
        public string GetUserInfoForJS()
        {
            DataTable dtUsers = new JH_Auth_UserB().GetDTByCommand(" SELECT UserName,UserRealName,BranchCode,JH_Auth_Branch.DeptName FROM JH_Auth_User INNER JOIN dbo.JH_Auth_Branch ON JH_Auth_User.BranchCode=JH_Auth_Branch.DeptCode ");
            //获取选择用户需要的HTML和转化用户名需要的json数据
            string strJsonUsers = "{";
            for (int i = 0; i < dtUsers.Rows.Count; i++)
            {
                strJsonUsers = strJsonUsers + "'" + dtUsers.Rows[i]["UserName"].ToString() + "':'" + dtUsers.Rows[i]["UserRealName"].ToString() + "',";

            }
            strJsonUsers = strJsonUsers.TrimEnd(',');
            strJsonUsers = strJsonUsers + "}";
            return strJsonUsers;
        }

        /// <summary>
        /// 获取前端需要的人员选择列表
        /// </summary>
        public string GetBranchForJS()
        {
            string strJsonBranchs = "{";
            List<JH_Auth_Branch> ListBranch = new JH_Auth_BranchB().GetEntities(d => d.DeptName != "").ToList();

            foreach (var item in ListBranch)
            {
                strJsonBranchs = strJsonBranchs + "'" + item.DeptCode + "':'" + item.DeptName + "',";

            }
            strJsonBranchs = strJsonBranchs.TrimEnd(',');
            strJsonBranchs = strJsonBranchs + "}";
            return strJsonBranchs;
        }



        /// <summary>
        /// 修改密码
        /// </summary>
        public void UpadteMiMa(string strUser, string strNewPassWord)
        {
            StringBuilder strAddAuthTree = new StringBuilder();
            JH_Auth_User UPUser = new JH_Auth_UserB().GetEntities(d => d.UserName == strUser).SingleOrDefault();
            UPUser.UserPass = strNewPassWord;
            new JH_Auth_UserB().Update(UPUser);
            //修改老数据库密码

            new JH_Auth_UserB().ExsSql(" UPDATE  jd.dbo.JH_Auth_User SET UserPass= '" + strNewPassWord + "' WHERE UserName='" + strUser + "'");

        }

        /// <summary>
        /// 加,号 获取去所在机构人员
        /// </summary>
        /// <param name="strBranchCode"></param>
        /// <returns></returns>
        public string GetAllUserListByBranch(int intBranchCode)
        {


            return new JH_Auth_UserB().GetEntities(d => d.BranchCode == intBranchCode).Select(d => d.UserName).ToList().ListTOString(',');


        }

    }

    //部门表
    public class JH_Auth_BranchB : BaseEFDao<JH_Auth_Branch>
    {
        /// <summary>
        /// 根据部门代码删除部门及部门人员
        /// </summary>
        /// <param name="intBranchCode"></param>
        public void DelBranchByCode(int intBranchCode)
        {
            new JH_Auth_BranchB().Delete(d => d.DeptCode == intBranchCode);
            new JH_Auth_UserB().Delete(d => d.BranchCode == intBranchCode);
        }

        /// <summary>
        /// 获取机构数用在assginuser.ASPX中
        /// </summary>
        /// <param name="intRoleCode">角色代码</param>
        /// <param name="intBranchCode">机构代码</param>
        /// <returns></returns>
        public string GetBranchUserTree(int intRoleCode, int intBranchCode)
        {
            StringBuilder strTree = new StringBuilder();
            var q = new JH_Auth_BranchB().GetEntities(d => d.DeptRoot == intBranchCode);
            foreach (var item in q)
            {
                strTree.AppendFormat("{{id:'{0}',pId:'{1}',name:'{2}',{3}}},", item.DeptCode, item.DeptRoot, item.DeptName, item.DeptRoot == -1 || item.DeptRoot == 0 ? "open:true" : "open:false");
                strTree.Append(GetUserByBranch(intRoleCode, item.DeptCode));
                strTree.Append(GetBranchUserTree(intRoleCode, item.DeptCode));
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }

        public string GetUserByBranch(int intRoleCode, int intBranchCode)
        {
            StringBuilder strTree = new StringBuilder();
            var q = new JH_Auth_UserB().GetEntities(d => d.BranchCode == intBranchCode);
            var query = from c in new JH_Auth_UserRoleB().GetEntities(ur => ur.RoleCode == intRoleCode)
                        select c.UserName;
            foreach (var item in q)
            {
                strTree.AppendFormat("{{id:'{0}',pId:'{1}',name:'{2}',isUser:'{3}',{4}}},", item.UserName, intBranchCode, item.UserRealName, "Y", query.Contains(item.UserName) ? "checked:true" : "checked:false");
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }


        /// <summary>
        /// 获取组织机构树
        /// </summary>
        /// <param name="intDeptCode">机构代码</param>
        /// <returns></returns>
        public string GetBranchTree(int intDeptCode)
        {
            StringBuilder strTree = new StringBuilder();
            var q = new JH_Auth_BranchB().GetEntities(d => d.DeptRoot == intDeptCode);
            foreach (var item in q)
            {
                strTree.AppendFormat("{{id:'{0}',pId:'{1}',attr:'{2}',name:'{3}',leader:'{4}',isuse:'{5}',order:'{6}'}},", item.DeptCode, item.DeptRoot, "Branch", item.DeptName, item.Remark1, item.Remark2, item.DeptShort);
                strTree.Append(GetBranchTree(item.DeptCode));
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }

        public string GetBranchNameByCode(int intDeptCode)
        {
            return new JH_Auth_BranchB().GetEntities(d => d.DeptCode == intDeptCode).SingleOrDefault().DeptName;
        }


    }



    //菜单权限表
    public class JH_Auth_MenuB : BaseEFDao<JH_Auth_Menu>
    {
        /// <summary>
        /// 判断用户是否有该菜单的权限
        /// </summary>
        /// <param name="strUserName">用户名称</param>
        /// <param name="strMenuCode">页面代码</param>
        /// <returns></returns>
        public bool IsHasMenuAuth(string strUserName, int intMenuCode)
        {
            bool IsHas = false;
            if (new JH_Auth_MenuB().GetEntities(u => u.isMenu == "Y" && u.IsUse == "Y" && u.AuthCode == intMenuCode).Count() == 0 || new JH_Auth_MenuB().GetDTByCommand("  select  top 1 UserName  from    [vw_JH_Auth_UserAuth] where   isMenu='Y' and IsUse='Y' and UserName='" + strUserName + "' and AuthCode='" + intMenuCode + "'").Rows.Count > 0)
            {
                IsHas = true;
            }
            return IsHas;
        }


        /// <summary>
        /// 获取用户一级的菜单
        /// </summary>
        /// <param name="strUserName">用户名</param>
        /// <returns></returns>
        public string GetMainMenuByUserName(string strUserName)
        {
            StringBuilder strMainMenu = new StringBuilder();
            DataTable dt = new JH_Auth_MenuB().GetDTByCommand(" select *   from    [vw_JH_Auth_UserAuth] where UserName='" + strUserName + "' and PAuthCode=1 and isMenu='Y' and IsUse='Y' ORDER BY  DisplayOrder ");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strMainMenu.AppendFormat("<li id='{0}'><a href='#'><img src='{2}' title='{3}' /><h2>{4}</h2></a></li>", dt.Rows[i]["AuthCode"].ToString(), dt.Rows[i]["FileName"].ToString() != "" ? dt.Rows[i]["FileName"] : "#", string.IsNullOrEmpty(dt.Rows[i]["Ico"].ToString()) ? "../images/icon02.png" : dt.Rows[i]["Ico"].ToString(), dt.Rows[i]["AuthName"].ToString(), dt.Rows[i]["AuthName"].ToString());
                }

            }
            return strMainMenu.ToString();
        }


        /// <summary>
        /// 根据用户名，父菜单代码获取用户可以查看的子菜单
        /// </summary>
        /// <param name="strUserName">用户代码</param>
        /// <param name="intPMenuCode">父菜单代码</param>
        /// <returns></returns>
        public string GetChiMenuByUserName(string strUserName, int intPMenuCode, DataTable ListAuth)
        {
            StringBuilder strMainMenu = new StringBuilder();
            DataTable dt = ListAuth.Where("PAuthCode = " + intPMenuCode).OrderBy("DisplayOrder");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strAuthName = dt.Rows[i]["AuthName"].ToString();
                int intAuthCode = int.Parse(dt.Rows[i]["AuthCode"].ToString());

                if (dt.Rows[i]["AuthLevel"].ToString() == "2")
                {
                    strMainMenu.Append("<dd><div class='title'><span><img src='../images/leftico01.png' /></span>" + strAuthName + "</div><ul class='menuson'>" + GetChiMenuByUserName(strUserName, intAuthCode, ListAuth) + "</ul></dd>");
                }
                if (dt.Rows[i]["AuthLevel"].ToString() == "3")
                {
                    string MenuUrl = dt.Rows[i]["FileName"].ToString();
                    if (MenuUrl.Contains('?'))
                    {
                        MenuUrl = MenuUrl + "&";
                    }
                    else
                    {
                        MenuUrl = MenuUrl + "?";

                    }
                    strMainMenu.Append("<li hrefurl='" + MenuUrl + "MenuCode=" + intAuthCode + "' id='" + intAuthCode + "'><cite></cite><a href='#'>" + strAuthName + "</a><i></i></li>");
                }
            }


            return strMainMenu.Length > 0 ? strMainMenu.ToString() : "";
        }




        /// <summary>
        /// 获得所有菜单
        /// </summary>
        /// <param name="intPAuthCode"></param>
        /// <returns></returns>
        public string GetAllAuth(int intPAuthCode)
        {
            StringBuilder strTree = new StringBuilder();
            var Results = new JH_Auth_MenuB().GetEntities(u => u.PAuthCode == intPAuthCode && u.isMenu == "Y");
            if (Results.Count() > 0)
            {
                foreach (var item in Results)
                {
                    strTree.AppendFormat("{{id:'{0}',pId:'{1}',level:'{2}',name:'{3}',taburl:'{4}',isuse:'{5}',menuicon:'{6}',{7},order:'{8}'}},", item.AuthCode, item.PAuthCode, item.AuthLevel, item.AuthName, item.FileName, item.IsUse, item.Ico, item.AuthLevel < 1 ? "open:true" : "open:false", item.DisplayOrder);
                    strTree.Append(GetAllAuth(item.AuthCode));
                }
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }




        /// <summary>
        /// 删除菜单（包括子菜单）
        /// </summary>
        /// <param name="MenuID"></param>
        /// <returns></returns>
        public bool DelAllMenuByID(int MenuID)
        {
            try
            {
                List<int> ListMenu = new List<int>();
                new JH_Auth_MenuB().GetMenuSByID(MenuID, ref ListMenu);
                new JH_Auth_MenuB().Delete(d => ListMenu.Contains(d.AuthCode));
                new JH_Auth_MenuB().Delete(d => d.AuthCode == MenuID);

                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        //获取菜单下所有子菜单（包含本身）
        public void GetMenuSByID(int MenuID, ref List<int> ListMenuID)
        {
            var q = new JH_Auth_MenuB().GetEntities(d => d.PAuthCode == MenuID);
            foreach (var item in q)
            {
                ListMenuID.Add(item.AuthCode);
                GetMenuSByID(item.AuthCode, ref ListMenuID);
            }
        }

    }

    //角色表
    public class JH_Auth_RoleB : BaseEFDao<JH_Auth_Role>
    {
        /// <summary>
        /// 获取角色树
        /// </summary>
        /// <param name="intRoleCode">角色代码</param>
        /// <returns></returns>
        public string GetRoleTree(int intRoleCode)
        {
            StringBuilder strTree = new StringBuilder();
            var q = new JH_Auth_RoleB().GetEntities(d => d.PRoleCode == intRoleCode);
            foreach (var item in q)
            {
                strTree.AppendFormat("{{id:'{0}',pId:'{1}',icon:'../../Image/admin/users.png',issys:'{2}',isuse:'{3}',name:'{4}',nodedec:'{5}'}},", item.RoleCode, item.PRoleCode, item.isSysRole, item.IsUse, item.RoleName, item.RoleDec);
                strTree.Append(GetRoleTree(item.RoleCode));
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="intRoleCode">角色代码</param>
        /// <returns></returns>
        public string delRole(int intRoleCode)
        {
            new JH_Auth_RoleB().Delete(d => intRoleCode == d.RoleCode && d.isSysRole != "Y");
            new JH_Auth_UserRoleB().Delete(d => intRoleCode == d.RoleCode);
            new JH_Auth_RoleAuthB().Delete(d => intRoleCode == d.RoleCode);
            return "Success";
        }

    }


    //角色权限表
    public class JH_Auth_RoleAuthB : BaseEFDao<JH_Auth_RoleAuth>
    {
        /// <summary>
        /// 获得角色的权限树
        /// </summary>
        /// <param name="intRoleCode"></param>
        /// <param name="intPAuthCode"></param>
        /// <returns></returns>
        public string GetRoleAuth(int intRoleCode, int intPAuthCode)
        {
            StringBuilder strTree = new StringBuilder();

            var Results = new JH_Auth_MenuB().GetEntities(d => d.PAuthCode == intPAuthCode);
            var query = from q in new JH_Auth_RoleAuthB().GetEntities(rm => rm.RoleCode == intRoleCode)
                        select q.AuthCode;
            if (Results.Count() > 0)
            {
                foreach (var item in Results)
                {
                    strTree.AppendFormat("{{id:'{0}',pId:'{1}',level:'{2}',name:'{3}',taburl:'{4}',isuse:'{5}',icon:'{6}',{7},{8}}},", item.AuthCode, item.PAuthCode, item.AuthLevel, item.AuthName, item.FileName, item.IsUse, item.Ico, query.Contains(item.AuthCode) ? "checked:true" : "checked:false", int.Parse(item.AuthLevel.ToString()) < 2 ? "open:true" : "open:false");
                    strTree.Append(GetRoleAuth(intRoleCode, item.AuthCode));
                }
            }
            return strTree.Length > 0 ? strTree.ToString() : "";
        }
        /// <summary>
        /// 为角色分配菜单
        /// </summary>
        /// <param name="arrMenuCodes">菜单代码</param>
        /// <param name="intRoleCode">角色代码</param>
        /// <returns></returns>
        public string AssignMenu(string[] arrMenuCodes, int intRoleCode)
        {
            try
            {
                //new JH_Auth_RoleAuthB().Delete(d => d.RoleCode == intRoleCode);
                foreach (string item in arrMenuCodes)
                {
                    JH_Auth_RoleAuth NewRoleMenu = new JH_Auth_RoleAuth();
                    NewRoleMenu.RoleCode = intRoleCode;
                    NewRoleMenu.AuthCode = int.Parse(item);
                    new JH_Auth_RoleAuthB().Insert(NewRoleMenu);
                }
                return "Success";
            }
            catch
            {
                return "Faile";
            }
        }
    }


    //用户角色表
    public class JH_Auth_UserRoleB : BaseEFDao<JH_Auth_UserRole>
    {


        /// <summary>
        /// 获取用户的角色代码
        /// </summary>
        /// <param name="strUserName">用户名</param>
        /// <returns></returns>
        public string GetRoleCodeByUserName(string strUserName)
        {
            string strRoleCode = "";
            var q = new JH_Auth_UserRoleB().GetEntities(d => d.UserName == strUserName);
            foreach (var item in q)
            {
                strRoleCode = strRoleCode + item.RoleCode.ToString() + ",";
            }
            return strRoleCode.TrimEnd(','); ;
        }



        /// <summary>
        ///  //删除角色权限关系
        /// </summary>
        /// <param name="strUserName">用户名</param>
        /// <param name="intRoleCode">角色代码</param>
        public void DelUserRole(string strUserName, int intRoleCode)
        {
            new JH_Auth_UserRoleB().Delete(d => d.UserName == strUserName && d.RoleCode == intRoleCode);
        }

        /// <summary>
        /// 为角色分配用户
        /// </summary>
        /// <param name="arrUserNames"></param>
        /// <param name="intRoleCode"></param>
        /// <returns></returns>
        public string AssignUser(string[] arrUserNames, int intRoleCode)
        {
            try
            {
                new JH_Auth_UserRoleB().Delete(d => d.RoleCode == intRoleCode);
                foreach (string item in arrUserNames)
                {
                    JH_Auth_UserRole NewUser_Role = new JH_Auth_UserRole();
                    NewUser_Role.RoleCode = intRoleCode;
                    NewUser_Role.UserName = item.ToString();
                    new JH_Auth_UserRoleB().Insert(NewUser_Role);
                }
                return "Success";
            }
            catch
            {
                return "Faile";
            }
        }
    }





    public class JH_Auth_FormBaseB : BaseEFDao<JH_Auth_FormBase>
    { }

    //附件表
    public class JH_Auth_FormAttchgB : BaseEFDao<JH_Auth_FormAttchg>
    {
        /// <summary>
        /// 插入并返回自增ID
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public string InsertList(IEnumerable<JH_Auth_FormAttchg> models)
        {
            if (Insert(models))
            {
                return string.Join(",", models.Select(o => o.id));
            }
            return string.Empty;
        }
    }


    public class ZH_XTGGB : BaseEFDao<ZH_XTGG>
    { }
    #endregion
}